package com.huatao.subject.infra.basic.service.impl;

import com.huatao.subject.common.entity.PageResult;
import com.huatao.subject.common.enums.SubjectInfoTypeEnum;
import com.huatao.subject.infra.basic.entity.EsSubjectFields;
import com.huatao.subject.infra.basic.entity.SubjectInfoEs;
import com.huatao.subject.infra.basic.es.EsIndexInfo;
import com.huatao.subject.infra.basic.es.EsRestClient;
import com.huatao.subject.infra.basic.es.EsSearchRequest;
import com.huatao.subject.infra.basic.es.EsSourceData;
import com.huatao.subject.infra.basic.service.SubjectEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
@Slf4j
public class SubjectEsServiceImpl implements SubjectEsService {

    @Override
    public boolean insert(SubjectInfoEs subjectInfoEs) {
        EsSourceData esSourceData = new EsSourceData();
        Map<String, Object> data = convertToEsSourceData(subjectInfoEs);
        esSourceData.setDocId(String.valueOf(subjectInfoEs.getDocId()));
        esSourceData.setData(data);
        return EsRestClient.insertDoc(getEsIndexInfo(), esSourceData);
    }

    private Map<String, Object> convertToEsSourceData(SubjectInfoEs subjectInfoEs) {
        Map<String, Object> data = new HashMap<>();
        data.put(EsSubjectFields.SUBJEC_ID, subjectInfoEs.getSubjectId());
        data.put(EsSubjectFields.DOC_ID, subjectInfoEs.getDocId());
        data.put(EsSubjectFields.SUBJEC_NAME, subjectInfoEs.getSubjectName());
        data.put(EsSubjectFields.SUBJEC_ANSWER,subjectInfoEs.getSubjectAnswer());
        data.put(EsSubjectFields.SUBJEC_TYPE, subjectInfoEs.getSubjectName());
        data.put(EsSubjectFields.CREATE_USER, subjectInfoEs.getCreateUser());
        data.put(EsSubjectFields.CREATE_TIME, subjectInfoEs.getCreateTime());
        return data;
    }

    @Override
    public PageResult<SubjectInfoEs> querySUbjectList(SubjectInfoEs subjectInfoEs) {
        PageResult<SubjectInfoEs> pageResult = new PageResult<>();
        EsSearchRequest esSearchRequest = createSearchListQuery(subjectInfoEs);
        SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        List<SubjectInfoEs> subjectInfoEsList = new LinkedList<>();
        SearchHits hits = searchResponse.getHits();
        if (hits == null || hits.getHits() == null) {
            pageResult.setPageNo(subjectInfoEs.getPageNo());
            pageResult.setPageSize(subjectInfoEs.getPageSize());
            pageResult.setRecords(subjectInfoEsList);
            pageResult.setTotal(0);
            return pageResult;
        }
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            SubjectInfoEs subjectInfoEs1 = convertResult(hit);
            if (Objects.nonNull(subjectInfoEs1)) {
                subjectInfoEsList.add(subjectInfoEs1);
            }
        }
        pageResult.setPageNo(subjectInfoEs.getPageNo());
        pageResult.setPageSize(subjectInfoEs.getPageSize());
        pageResult.setRecords(subjectInfoEsList);
        pageResult.setTotal(Long.valueOf(hits.getTotalHits().value).intValue());
        return null;
    }

    private SubjectInfoEs convertResult(SearchHit hit) {
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        if (CollectionUtils.isEmpty(sourceAsMap)) {
            return null;
        }
        SubjectInfoEs result = new SubjectInfoEs();
        result.setSubjectId(MapUtils.getLong(sourceAsMap, EsSubjectFields.SUBJEC_ID));
        result.setSubjectName(MapUtils.getString(sourceAsMap, EsSubjectFields.SUBJEC_NAME));
        result.setSubjectAnswer(MapUtils.getString(sourceAsMap, EsSubjectFields.SUBJEC_ANSWER));
        result.setDocId(MapUtils.getLong(sourceAsMap, EsSubjectFields.DOC_ID));
        result.setSubjectType(MapUtils.getInteger(sourceAsMap, EsSubjectFields.SUBJEC_TYPE));
        result.setScore(new BigDecimal(String.valueOf(hit.getScore())).multiply(new BigDecimal("100.00")).setScale(2, RoundingMode.HALF_DOWN));
        // 处理name的高亮
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField subjectNameHighlight = highlightFields.get(EsSubjectFields.SUBJEC_NAME);
        if (Objects.nonNull(subjectNameHighlight)) {
            Text[] fragments = subjectNameHighlight.getFragments();
            StringBuilder sb = new StringBuilder();
            for (Text fragment: fragments) {
                sb.append(fragment);
            }
            result.setSubjectName(sb.toString());
        }
        // 处理答案的高亮
        HighlightField subjectAnswerHighlight = highlightFields.get(EsSubjectFields.SUBJEC_ANSWER);
        if (Objects.nonNull(subjectAnswerHighlight)) {
            Text[] fragments = subjectAnswerHighlight.getFragments();
            StringBuilder sb = new StringBuilder();
            for (Text fragment: fragments) {
                sb.append(fragment);
            }
            result.setSubjectAnswer(sb.toString());
        }
        return result;
    }

    private EsSearchRequest createSearchListQuery(SubjectInfoEs subjectInfoEs) {
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        BoolQueryBuilder bq = new BoolQueryBuilder();
        MatchQueryBuilder subjectNameQueryBuilder = QueryBuilders.matchQuery(EsSubjectFields.SUBJEC_NAME, subjectInfoEs.getKeyWords());
        bq.should(subjectNameQueryBuilder);
        subjectNameQueryBuilder.boost(2);
        MatchQueryBuilder subjectAnswerQueryBuilder = QueryBuilders.matchQuery(EsSubjectFields.SUBJEC_ANSWER, subjectInfoEs.getKeyWords());
        bq.should(subjectAnswerQueryBuilder);
        MatchQueryBuilder subjectTypeQueryBuilder = QueryBuilders.matchQuery(EsSubjectFields.SUBJEC_TYPE, SubjectInfoTypeEnum.BRIFE.getCode());
        bq.must(subjectTypeQueryBuilder);
        bq.minimumShouldMatch(1);
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags("<span style=\"color:red\">");
        highlightBuilder.postTags("</span>");
        esSearchRequest.setBq(bq);
        esSearchRequest.setHighlightBuilder(highlightBuilder);
        esSearchRequest.setFields(EsSubjectFields.FIELD_QUERY);
        esSearchRequest.setFrom((subjectInfoEs.getPageNo() - 1) * subjectInfoEs.getPageSize());
        esSearchRequest.setSize(subjectInfoEs.getPageSize());
        esSearchRequest.setNeedScroll(false);
        return esSearchRequest;
    }

    private EsIndexInfo getEsIndexInfo() {
        EsIndexInfo esIndexInfo = new EsIndexInfo();
        esIndexInfo.setClusterName("8772573ed134");
        esIndexInfo.setIndexName("subject_index");
        return esIndexInfo;
    }
}
